<template>
    <div>
        <el-table
            :data="tableData" border
            tooltip-effect="dark" @selection-change="handleSelectionChange"
            style="width: 100%;text-align: center">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column fixed="left"
                prop="itemNum"
                label="物资编码,Item Code"
                min-width="120px" :render-header="renderHeader">
            </el-table-column>
            <el-table-column
                prop="itemDescription"
                label="物资描述,Item Description"
                min-width="260px" :render-header="renderHeader">
            </el-table-column>
            <el-table-column
                prop="quantityBasedOnMoq"
                label="最小订货量,MOQ"
                min-width="120px" :render-header="renderHeader">
            </el-table-column>
            <el-table-column
                prop="quantity"
                label="数量,Quantity"
                min-width="150px" :render-header="renderHeader">
                <template slot-scope="scope">
                    <EditableCell :scope="scope" @getMaterialList="getMaterialList"/>
                </template>
            </el-table-column>
            <el-table-column
                prop="costCenter"
                label="成本中心,Cost Center"
                min-width="260px" :render-header="renderHeader">
                <template slot-scope="scope">
                    <CostCenterSelect :scope="scope" :costCenterList="costCenterList"  @getMaterialList="getMaterialList"/>
                </template>
            </el-table-column>
            <el-table-column
                prop="requiredDate"
                label="需求日期,Required Date"
                min-width="260px" :render-header="renderHeader">
                <template slot-scope="scope">
                    <el-date-picker
                        @change="(value) => pickerChange(scope.row, value)"
                        value-format="yyyy-MM-dd"
                        v-model="scope.row.requiredDate"
                        type="date"
                        placeholder="选择日期">
                    </el-date-picker>
                </template>
            </el-table-column>
            <el-table-column fixed="right"
                prop="operation"
                label="操作,Operation"
                min-width="100px" :render-header="renderHeader">
                <template slot-scope="scope">
                    <el-tooltip content="Delete" placement="top">
                        <el-button type="text" style="font-size: 24px" @click="applyDelete(scope.row)"
                                   class="el-icon-delete">
                        </el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <PaginationMode :pageData="pageData" @onPageChange="onPageChange" />
        <el-row :gutter="24">
            <el-col :span="2" :offset="17" style="margin-bottom: 30px">
                <el-tooltip content="Submit" placement="top">
                    <el-button type="success" round icon="el-icon-upload2" @click="() => SubmitPreviewShow('submit')">提交</el-button>
                </el-tooltip>
            </el-col>
            <el-col :span="2">
                <el-tooltip content="Save" placement="top">
                    <el-button type="primary" round icon="el-icon-check" @click="() => SubmitPreviewShow('save')">保存</el-button>
                </el-tooltip>
            </el-col>
            <el-col :span="2">
                <el-tooltip content="Delete" placement="top">
                    <el-button type="info" round icon="el-icon-delete" @click="batchDelete">批量删除</el-button>
                </el-tooltip>
            </el-col>
        </el-row>
        <!--提交预览-->
        <SubmitPreview :submitPreviewVisible="submitPreviewVisible" :applyNo="applyNo" :applyId="applyId"
                       @CloseSubmitPreview="CloseSubmitPreview" @showPromptSubmit="showPromptSubmit" />
        <!--是否加入常用物料单-->
        <RequestPrompt :noteDescribeVisible="noteDescribeVisible"  :applyNo="applyNo" @submitResetData="submitResetData"
                       @hiddenPromptSubmit="hiddenPromptSubmit" @showRemarksMode="showRemarksMode" />
        <!--加入常用物料单弹窗-->
        <RemarksMode :remarksModeVisible="remarksModeVisible" @hiddenRemarksMode="hiddenRemarksMode" :applyId="applyId" />
        <!--保存弹窗-->
        <RequestFormSave :requestFormSaveVisible="requestFormSaveVisible" @hiddenRequestFormSave="hiddenRequestFormSave"
                         :applyNo="applyNo" />
    </div>
</template>

<script>
import { applicationMaterialList, applyUpdateMaterial, delMaterial,
    batchDelMaterial, getTemporary, getApplyUpdate } from "../../../components/axios/url";
import http from "../../../components/axios/fetch";
import bus, {TYPES} from "../../common/bus";
import {getOrganizationList} from "../../helpers/CommonSlect";
import CommonSlectList from "../../helpers/CommonSlect";
import CostCenterSelect from "./CostCenterSelect";
import EditableCell from "./EditableCell";
import PaginationMode from '../../common/Pagination.vue';
import SubmitPreview from "./SubmitPreview";
import RequestPrompt from "./RequestPrompt";
import RemarksMode from "./RemarksMode";
import RequestFormSave from "./RequestFormSave";
import renderHeader from '../../common/renderHeader.js';
import { TimeUtil } from '@eku/eku-tools';

    export default {
        name: "applicationList",
        components: {
            CostCenterSelect,
            PaginationMode,
            EditableCell,
            SubmitPreview,
            RequestPrompt,
            RemarksMode,
            RequestFormSave
        },
        props: {
            applyId: '',
            applyNo: '',
        },
        data() {
            return {
                keyword: null,
                page: 1,
                tableData: [],
                pageData: {},
                time: "",
                multipleSelection: [],
                submitPreviewVisible: false,
                ruleForm: {},
                noteDescribeVisible: false,
                remarksModeVisible: false,
                requestFormSaveVisible: false,
                reviewStatus: null, // 判断是否有更改原因
            }
        },
        mixins: [CommonSlectList],
        mounted(){
            bus.$on(TYPES.tabType, (name)=>{
                if(name === 'application') {
                    this.getMaterialList();
                }
            });
            bus.$on(TYPES.updataApplicationForm, (data)=>{
                this.ruleForm = data.ruleForm
                this.reviewStatus = data.reviewStatus || null
            });
            this.getCostCenterList();
        },
        methods: {
            renderHeader: renderHeader,
            async getMaterialList() { // 列表请求
                try{
                   let res=  await http.post(applicationMaterialList, {
                        page: this.page,
                        applyId: this.applyId
                    });

                    if(res.data && res.data.resultMess === "success") {
                        this.tableData = res.data.data.list
                        this.pageData = res.data.data.page
                    }
                } catch (e){
                    this.$notify.error({
                        title: '提示',
                        message: '网络错误',
                    });
                }
            },
            onPageChange(page) { // 分页
                this.page = page;
                this.getMaterialList();
            },
            pickerChange(record, time) { // 需求日期
                let param = {
                    id: record.id,
                    requiredDate: time
                }
                try{
                    http.post(applyUpdateMaterial, param).then(res => {
                        if(res.data && res.data.resultMess === "success") {
                            this.$notify({
                                title: '提示',
                                message: '修改成功',
                                type: 'success'
                            });
                        }
                    })
                }catch(error){
                    this.$notify.error({
                        title: '提示',
                        message: '网络错误',
                    });
                }
            },
            applyDelete(record) { // 单个删除
                try{
                    http.post(delMaterial, {materialId: record.id}).then(res => {
                        if(res.data && res.data.resultMess === "success") {
                            this.$notify({ title: '提示', message: '刪除成功', type: 'success' });
                            this.getMaterialList();
                            this.$emit('getMaterialTotal');
                        }
                    })
                }catch(error){
                    this.$notify.error({ title: '提示', message: '网络错误' });
                }

            },
            handleSelectionChange(val) { // 勾选数据
                this.multipleSelection = val;
            },
            batchDelete() { // 批量删除
                if(this.multipleSelection.length === 0) {
                    this.$notify({ title: '提示', message: '请选勾选要删除的物资', type: 'warning' });
                    return;
                }
                let list = []
                this.multipleSelection.forEach((item) => {
                    list.push(item.id)
                })
                const materialList = this.multipleSelection.map((item) => (item.id));
                try{
                    http.post(batchDelMaterial, {materialIds: materialList.toString()}).then(res => {
                        if(res.data && res.data.resultMess === "success") {
                            this.multipleSelection = [];
                            this.$emit('getMaterialTotal');
                            this.$notify({ title: '提示', message: '删除成功', type: 'success' });
                        }
                    })
                }catch(error){
                    this.$notify.error({
                        title: '提示',
                        message: '网络错误',
                    });
                }
            },
            SubmitPreviewShow(type) {  // 提交预览
                let ruleForm = this.ruleForm;
                if(ruleForm && ruleForm.workGroupId === null) {
                    this.$notify({ title: '提示', message: '请选择部门', type: 'warning' });
                    return;
                }
                if(ruleForm && ruleForm.purchaseTypeId === null) {
                    this.$notify({ title: '提示', message: '请选择购买类型', type: 'warning' });
                    return;
                }
                if(ruleForm && ruleForm.deliverySiteId === null) {
                    this.$notify({ title: '提示', message: '请选择交付地点', type: 'warning' });
                    return;
                }
                if(this.reviewStatus && ruleForm.changeReason === null) {
                    this.$notify({ title: '提示', message: '请输入更改原因', type: 'warning' });
                    return;
                }
                if(this.tableData && this.tableData.length === 0) {
                    this.$notify({ title: '提示', message: '请选择物资', type: 'warning' });
                    return;
                }

                let time = new Date().getTime(); // 当前日期
                let param = {
                    id: this.applyId,
                    applyTime: TimeUtil.formatDate(time, 'yyyy-MM-dd HH:mm:ss'),
                    ...ruleForm,
                };

                if(type === 'submit') {  // 提交
                    // 暂存表头信息
                    try{
                        http.post(getTemporary, param).then(res => {
                            if(res.data && res.data.resultMess === "success") {
                                this.showSubmitPreview() // 显示预览弹窗
                            }
                        })
                    }catch(error){
                        this.$notify.error({ title: '提示', message: '网络错误' });
                    }
                }

                if(type === 'save') {  // 保存
                    try{
                        http.post(getApplyUpdate, {...param, status: 1}).then(res => {
                            if(res.data && res.data.resultMess === "success") {
                                this.showRequestFormSave();
                            }
                        })
                    }catch(error){
                        this.$notify.error({ title: '提示', message: '网络错误' });
                    }
                }
            },
            showSubmitPreview() {  //提交预览
                this.submitPreviewVisible = true
            },
            CloseSubmitPreview() {  // 关闭提交预览
                this.submitPreviewVisible = false
            },
            showPromptSubmit(){ //显示是否加入物料弹框
                this.noteDescribeVisible = true;
            },
            hiddenPromptSubmit(){ //隐藏是否加入物料框
                this.noteDescribeVisible = false;
            },
            showRemarksMode() { // 显示加入常用物料单
                this.remarksModeVisible = true;
            },
            hiddenRemarksMode() {// 关闭加入常用物料单
                this.remarksModeVisible = false;
                this.submitResetData();
            },
            showRequestFormSave() { // 显示保存弹窗
                this.requestFormSaveVisible = true;
            },
            hiddenRequestFormSave() { // 关闭保存弹窗
                this.requestFormSaveVisible = false;
                this.submitResetData();
            },
            submitResetData() { // 清除缓存
                if(this.$route.query && this.$route.query.modeType === 'edit') {
                    this.$router.push('/platform/Application');
                }
                this.$emit('getApplyNo'); // 创建新单
                this.$emit('tabInit'); // 提交完初始化Tab 值
                this.$emit('resetFormData'); // 清除表头数据
                this.$emit('getMaterialTotal'); // 初始化购物车数量
            }
        }
    }
</script>

<style scoped>

</style>
